const { Service } = require('egg')
const { tableToList } = require('../utils/tools')

module.exports = class SinfoService extends Service {
  /**
   * * 学籍卡片信息
   * @return {Object} *
   */
  async table() { // !可能出现只能单人使用,逻辑处理不行
    // const Cookie = this.ctx.state.Cookie;
    // console.log('Cookie', Cookie);
    const Cookie = this.ctx.state.Cookie
    console.log('Cookie', Cookie)
    const CookieExp = this.ctx.state.CookieExp
    console.log('CookieExp', CookieExp)
    const apiUrl = `${this.ctx.state.baseUrl}/eams/stdInfoApply!innerIndex.action?projectId=1&_=1713486376875`
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const info = {}
    console.log('res', res)
    // console.log('res.data', res.data.toString());

    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#tabPage1')
        // console.log('tableList', tableList);
        // const info = {}
        tableList.filter((e) => e).slice(1, 6).forEach((e, i) => {
          console.log(e, i)
          let key = ''
          /* 处理性别 */
          if (i === 1) {
            e.filter((ee) => ee).slice(0, 2).forEach((ee, j) => {
              // console.log(e, j);
              const eee = ee.replace(/：$/, '')
              console.log(eee)
              if (j % 2 === 0) {
                info[eee] = ''
                key = eee
              }
              else info[key] = eee
            })
          }
          /* 处理学制 */
          else if (i === 3) {
            e.filter((ee) => ee).slice(1, 3).forEach((ee, j) => {
              // console.log(e, j);
              const eee = ee.replace(/：$/, '')
              console.log(eee)
              if (j % 2 === 0) {
                info[eee] = ''
                key = eee
              }
              else info[key] = eee
            })
          }
          /* 处理院系、主专、班级、姓名、学号 */
          else {
            e.filter((ee) => ee).forEach((ee, j) => {
              // console.log(e, j);
              const eee = ee.replace(/：$/, '')
              console.log(eee)
              if (j % 2 === 0) {
                info[eee] = ''
                key = eee
              }
              else info[key] = eee
            })
          }
        })

        return info
      } catch (err) {
        console.log(err)
        throw err
      }
    }
    return info
  }
}
